package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    //本地注入DAO
    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        //调用DAO层
        Page<CheckItem> page = checkGroupDao.selectByCondition(queryString);

        return new PageResult(page.getTotal(), page.getResult());
    }

    //新增检查组
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.add(checkGroup);
        setCheckItemAndCheckGroup(checkGroup.getId(), checkitemIds);
    }

    //关联检查项和检查组
    public void setCheckItemAndCheckGroup(Integer checkgroupId, Integer[] checkitemIds) {
        //判断checkitemIds是否为空
        if (checkitemIds != null && checkitemIds.length > 0) {
            //遍历
            for (Integer checkitemId : checkitemIds) {
                //创建map集合,用于存储检查组合检查项的id
                Map<String, Integer> map = new HashMap<>();
                //添加对应的值
                map.put("checkgroupId_id", checkgroupId);
                map.put("checkitemId_id", checkitemId);
                //调用DAO层
                checkGroupDao.setCheckItemAndCheckGroup(map);
            }
        }
    }

    //根据id查询检查组信息
    @Override
    public CheckGroup findById(Integer checkgroupId) {
        return checkGroupDao.findById(checkgroupId);
    }

    //查询所有检查项信息
    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }

    //根据检查组id查询检查项id
    @Override
    public Integer[] findCheckItemIdByCheckGroupId(Integer checkgroupId) {
        return checkGroupDao.findCheckItemIdByCheckGroupId(checkgroupId);
    }

    //修改检查组
    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        Integer checkGroupId = checkGroup.getId();
        //调用DAO层,修改表单
        checkGroupDao.editFormData(checkGroup);
        //删除当前检查组和检查项关联的内容
        checkGroupDao.deleteAssociatedInfo(checkGroupId);
        //添加现在的关联关系
        setCheckItemAndCheckGroup(checkGroupId, checkitemIds);
    }
}
